from ST7735 import TFT,bitSwap
from machine import SPI,Pin
import time
import network
import ntptime
from bmpE import show_pic

#hardware SPI, HSPI
spi=SPI(1,baudrate=40000000, polarity=0, phase=0, sck=Pin(2), mosi=Pin(3))
tft=TFT(spi,'/combined.bin',6,10,7)# dc, rst, cs   #6,10,7 aDC, aReset, aCS
tft.rgb(False)
tft.init_7735(tft.REDTAB80x160)
counts = 1

# network connect
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

ntptime.host = 'ntp1.aliyun.com'  # 设置NTP服务器

led1 = Pin(12, Pin.OUT)
led2 = Pin(13, Pin.OUT)
def ledFlash(t, tt):
    led1.on()
    time.sleep(t)
    led2.on()
    time.sleep(t)
    led1.off()
    time.sleep(t)
    led2.off()
    time.sleep(tt)

while True:
    
    if wlan.isconnected():
        ip_address = wlan.ifconfig()[0]
        ntptime.settime()
        pass
    else:
        try:
            wlan.connect('name', 'passwd') # replace by your wifi setting
            ip_address = wlan.ifconfig()[0]
            ntptime.settime()
            print(ip_address)
        except:
            try:
                wlan.connect('name2', 'passwd2') # replace by your backup wifi setting
                ip_address = wlan.ifconfig()[0]
                ntptime.settime()
                print(ip_address)
            except:
                print('failed to connect')
                ip_address = "No_Internet"
        
    tft.fill(TFT.WHITE)
    chars = 'IP:' + str(ip_address)
    tft.text((10,25),chars,TFT.BLACK,(1,2))
    ledFlash(0.1, 1)
    
    tft.fill(TFT.WHITE)
    chars = '卑鄙是卑鄙者的通行证.高尚是高尚者的墓志铭.'
    tft.text((10,20),chars,bitSwap(TFT.BLACK),(1,1))
    ledFlash(0.2, 3)
          
    tft.fill(TFT.WHITE)
    chars = f"本次功德-----" + str(counts)
    counts += 1
    tft.text((10,10),chars,TFT.CYAN,(2,2))
    ledFlash(0.3, 1)
    
    mytime = time.localtime()

    # 获取小时、分钟和秒，并添加零前缀
    hours = (mytime[3] + 8) % 24
    minutes = mytime[4]
    seconds = mytime[5]

    hours_str = f'{hours:02d}'
    minutes_str = f'{minutes:02d}'
    seconds_str = f'{seconds:02d}'

    Ltime = f'{mytime[0]}-{mytime[1]}-{mytime[2]}----{hours_str}:{minutes_str}'
        
    tft.fill(TFT.WHITE)
    chars = str(Ltime)
    tft.text((0,10),chars,TFT.RED,(2,2))
    ledFlash(0.5, 1)
    
    tft.rotation(0)
    show_pic("t1.bmp")
    ledFlash(1, 2)
#     show_pic("t2.bmp")
#     ledFlash()
    tft.rotation(1)
